package org.timeismoney.payment.web;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import org.timeismoney.payment.common.PageBean;

public class WebUtils {

	@SuppressWarnings("rawtypes")
	public static String generateJSONByPageBean(PageBean pageBean) {
		String json = "{\"page\":\"" + pageBean.getCurrentPage()
				+ "\",\"total\":" + pageBean.getTotalPages()
				+ ",\"records\":\"" + pageBean.getTotalRows() + "\",\"rows\":";
		JsonConfig jc = new JsonConfig();
		decorateJSONConfig(jc);
		json += JSONSerializer.toJSON(pageBean.getItems(), jc) + "}";
		return json;
	}

	@SuppressWarnings("rawtypes")
	public static String generateJSONByPageBean(PageBean pageBean,
			JsonConfig config) {
		if (config == null)
			return generateJSONByPageBean(pageBean);
		String json = "{\"page\":\"" + pageBean.getCurrentPage()
				+ "\",\"total\":" + pageBean.getTotalPages()
				+ ",\"records\":\"" + pageBean.getTotalRows() + "\",\"rows\":";
		json += JSONSerializer.toJSON(pageBean.getItems(), config).toString()
				+ "}";
		return json;
	}
	
	@SuppressWarnings("rawtypes")
	public static String generateSubGridJSONByCollection(Collection c) {
		JsonConfig jc = new JsonConfig();
		decorateJSONConfig(jc);
		String json = "{\"rows\":"+JSONSerializer.toJSON(c, jc).toString()+"}";
		return json;
	}

	@SuppressWarnings("rawtypes")
	public static String generateJSONByCollection(Collection c) {
		JsonConfig jc = new JsonConfig();
		decorateJSONConfig(jc);
		return JSONSerializer.toJSON(c, jc).toString();
	}
	
	public static String generateSuccessJSON(String message) {
		return "{\"success\":\"" + message + "\"}";
	}

	public static String generateErrorJSON(String message) {
		return "{\"errorMsg\":\"" + message + "\"}";
	}
	
	private static void decorateJSONConfig(JsonConfig jc){
		jc.setJsonPropertyFilter(new JSONHelper.IgnoreProxyObj4JSONFilter());
		jc.registerJsonValueProcessor(Date.class, new JSONHelper.DateJsonValueProcessor());
	}

	public final static String getTimeString() {
		StringBuilder timeString = new StringBuilder("");
		Calendar c = Calendar.getInstance();

		int yyyy = c.get(Calendar.YEAR);
		int mm = c.get(Calendar.MONTH) + 1;
		int dd = c.get(Calendar.DAY_OF_MONTH);
		int hh = c.get(Calendar.HOUR_OF_DAY);
		int MM = c.get(Calendar.MINUTE);

		String sMonth = mm < 10 ? "0" + mm : "" + mm;
		String sDay = dd < 10 ? "0" + dd : "" + dd;
		String sHour = hh < 10 ? "0" + hh : "" + hh;
		String sMinute = MM < 10 ? "0" + MM : "" + MM;

		timeString.append(yyyy).append(sMonth).append(sDay).append(sHour).append(sMinute);

		return timeString.toString();
	}
}
